import Mock from 'mockjs'

// 仅 H5 端使用：通过 Mock.js 拦截同源 XHR 请求（由 request.js 按需动态导入）
// 同时补充 fetch 拦截，兼容 uni.request 在 H5 下可能采用的 fetch 实现

// 收集已注册的路由，便于 fetch 拦截复用
const __routes = []
const __originMock = Mock.mock
Mock.mock = function (rurl, rtype, template) {
  try {
    __routes.push({ rurl, rtype: (rtype || 'get').toLowerCase(), template })
  } catch (e) {}
  return __originMock.call(this, rurl, rtype, template)
}

// 注入 fetch 拦截（仅浏览器环境）
if (typeof window !== 'undefined' && typeof window.fetch === 'function') {
  const __origFetch = window.fetch.bind(window)
  window.fetch = async (input, init = {}) => {
    try {
      const url = typeof input === 'string' ? input : (input && input.url) || ''
      const method = ((init && init.method) || 'GET').toLowerCase()
      for (const route of __routes) {
        const okMethod = !route.rtype || route.rtype === method
        const okUrl = route.rurl instanceof RegExp
          ? route.rurl.test(url)
          : (typeof route.rurl === 'string' ? url.includes(route.rurl) : false)
        if (okMethod && okUrl) {
          const tpl = route.template
          const payload = typeof tpl === 'function' ? tpl({ url, type: method }) : __originMock(tpl)
          // 模拟网络延迟，与 Mock.setup(timeout) 保持一致的体验
          const delay = () => new Promise(r => setTimeout(r, Math.floor(Math.random() * 401) + 200))
          await delay()
          return new Response(JSON.stringify(payload), {
            status: 200,
            headers: { 'Content-Type': 'application/json' }
          })
        }
      }
    } catch (e) {
      // 忽略异常，回落到真实 fetch
    }
    return __origFetch(input, init)
  }
}

// 使用国内可访问的免费图片（Pexels CDN），自定义占位符 @cnImage("WxH")
const __pexelsIds = [
  1546896, 1108099, 209206, 1391487, 1640777, 373873, 34950, 277253, 298863, 248616
]
Mock.Random.extend({
  cnImage (size = '200x200') {
    try {
      const parts = String(size).toLowerCase().split('x')
      const w = parseInt(parts[0]) || 200
      const h = parseInt(parts[1] || parts[0]) || w
      const id = this.pick(__pexelsIds)
      return `https://images.pexels.com/photos/${id}/pexels-photo-${id}.jpeg?auto=compress&cs=tinysrgb&fit=crop&w=${w}&h=${h}`
    } catch (e) {
      // 兜底：使用 Mock 自带的 dataURL 占位图，保证不报错（避免与覆盖后的 image 形成递归）
      return Mock.Random.dataImage(size, 'placeholder')
    }
  }
})

// 全局覆盖：将 Mock.Random.image 重定向到 cnImage，保持 @image("WxH") 写法可用
// 仅使用第一个 size 参数，忽略其他参数，保证兼容性
Mock.Random.image = function (size) {
  return Mock.Random.cnImage(size)
}

// 设置延迟时间
Mock.setup({
  timeout: '200-600'
})

// 提供显式的本地匹配调用，便于在 H5 下直接走本地返回，避免发起真实网络请求
export async function mockFetch (url, method = 'GET', body = undefined) {
  try {
    const m = (method || 'GET').toLowerCase()
    for (const route of __routes) {
      const okMethod = !route.rtype || route.rtype === m
      const okUrl = route.rurl instanceof RegExp
        ? route.rurl.test(url)
        : (typeof route.rurl === 'string' ? url.includes(route.rurl) : false)
      if (okMethod && okUrl) {
        const tpl = route.template
        const payload = typeof tpl === 'function'
          ? tpl({ url, type: m, body })
          : __originMock(tpl)
        const delay = () => new Promise(r => setTimeout(r, Math.floor(Math.random() * 401) + 200))
        await delay()
        return payload
      }
    }
  } catch (e) {}
  return null
}

// 用户相关Mock数据
Mock.mock(/\/api\/auth\/login/, 'post', {
  code: 0,
  message: '登录成功',
  data: {
    token: '@guid',
    userInfo: {
      id: '@id',
      openid: '@guid',
      nickname: '@cname',
      avatar: '@image("100x100")',
      phone: /^1[3-9]\d{9}$/,
      balance: '@float(0, 1000, 2, 2)',
      referrer_id: '@id',
      created_at: '@datetime'
    }
  }
})

Mock.mock(/\/api\/user\/info/, 'get', {
  code: 0,
  message: '获取成功',
  data: {
    id: '@id',
    openid: '@guid',
    nickname: '@cname',
    avatar: '@image("100x100")',
    phone: /^1[3-9]\d{9}$/,
    balance: '@float(0, 1000, 2, 2)',
    referrer_id: '@id',
    created_at: '@datetime'
  }
})

// 更新用户信息（PUT）
Mock.mock(/\/api\/user\/info/, 'put', {
  code: 0,
  message: '更新成功',
  data: true
})

// 用户邀请记录
Mock.mock(/\/api\/user\/invite-records/, 'get', {
  code: 0,
  message: '获取成功',
  data: {
    'list|5-15': [
      {
        id: '@id',
        nickname: '@cname',
        avatar: '@image("50x50")',
        created_at: '@datetime',
        reward: '@float(0, 20, 2, 2)'
      }
    ],
    total: '@integer(5, 200)'
  }
})

// 用户佣金记录
Mock.mock(/\/api\/user\/commission-records/, 'get', {
  code: 0,
  message: '获取成功',
  data: {
    'list|10-30': [
      {
        id: '@id',
        type: '@pick(["order","invite","adjust"])',
        amount: '@float(0, 100, 2, 2)',
        created_at: '@datetime',
        remark: '@ctitle(6, 16)'
      }
    ],
    total: '@integer(10, 300)'
  }
})

Mock.mock(/\/api\/user\/balance/, 'get', {
  code: 0,
  message: '获取成功',
  data: {
    balance: '@float(0, 1000, 2, 2)',
    frozen_balance: '@float(0, 100, 2, 2)'
  }
})

// 商品相关Mock数据
Mock.mock(/\/api\/goods\/home/, 'get', {
  code: 0,
  message: '获取成功',
  data: {
    banners: [
      {
        id: '@id',
        image: '@image("750x300")',
        title: '@ctitle(10, 20)',
        link: '@url'
      }
    ],
    seckill: {
      title: '限时秒杀',
      end_time: '@datetime',
      goods: [
        {
          id: '@id',
          name: '@ctitle(5, 15)',
          image: '@image("200x200")',
          original_price: '@float(10, 100, 2, 2)',
          seckill_price: '@float(5, 50, 2, 2)',
          stock: '@integer(1, 100)',
          sold_count: '@integer(0, 50)'
        }
      ]
    },
    recommend: {
      title: '团长推荐',
      goods: [
        {
          id: '@id',
          name: '@ctitle(5, 15)',
          image: '@image("200x200")',
          price: '@float(10, 100, 2, 2)',
          original_price: '@float(15, 120, 2, 2)',
          leader_name: '@cname',
          leader_avatar: '@image("50x50")',
          commission_rate: '@float(5, 15, 1, 1)'
        }
      ]
    }
  }
})

Mock.mock(/\/api\/goods\/categories/, 'get', {
  code: 0,
  message: '获取成功',
  data: [
    {
      id: '@id',
      name: '生鲜果蔬',
      icon: '@image("50x50")',
      children: [
        {
          id: '@id',
          name: '新鲜水果',
          image: '@image("100x100")'
        },
        {
          id: '@id',
          name: '时令蔬菜',
          image: '@image("100x100")'
        }
      ]
    },
    {
      id: '@id',
      name: '肉禽蛋奶',
      icon: '@image("50x50")',
      children: [
        {
          id: '@id',
          name: '新鲜肉类',
          image: '@image("100x100")'
        },
        {
          id: '@id',
          name: '禽蛋奶类',
          image: '@image("100x100")'
        }
      ]
    }
  ]
})

Mock.mock(/\/api\/goods\/detail\/\d+/, 'get', {
  code: 0,
  message: '获取成功',
  data: {
    id: '@id',
    name: '@ctitle(10, 20)',
    description: '@cparagraph(3, 7)',
    images: [
      '@image("400x400")',
      '@image("400x400")',
      '@image("400x400")'
    ],
    price: '@float(10, 100, 2, 2)',
    original_price: '@float(15, 120, 2, 2)',
    stock: '@integer(1, 1000)',
    sold_count: '@integer(0, 500)',
    leader: {
      id: '@id',
      name: '@cname',
      avatar: '@image("100x100")',
      store_name: '@ctitle(5, 10)',
      commission_rate: '@float(5, 15, 1, 1)',
      service_radius: '@integer(1000, 5000)'
    },
    specifications: [
      {
        name: '规格',
        values: ['500g', '1kg', '2kg']
      },
      {
        name: '包装',
        values: ['散装', '盒装', '袋装']
      }
    ],
    is_seckill: '@boolean',
    seckill_price: '@float(5, 50, 2, 2)',
    seckill_end_time: '@datetime'
  }
})

// 购物车相关Mock数据
Mock.mock(/\/api\/cart\/list/, 'get', {
  code: 0,
  message: '获取成功',
  data: [
    {
      id: '@id',
      goods_id: '@id',
      goods_name: '@ctitle(5, 15)',
      goods_image: '@image("100x100")',
      price: '@float(10, 100, 2, 2)',
      quantity: '@integer(1, 10)',
      selected: '@boolean',
      leader_name: '@cname',
      stock: '@integer(1, 100)'
    }
  ]
})

// 订单相关Mock数据
Mock.mock(/\/api\/order\/list/, 'get', {
  code: 0,
  message: '获取成功',
  data: {
    'list|5-10': [
      {
        id: '@id',
        order_no: '@string("number", 16)',
        status: '@pick(["pending_pay", "pending_accept", "accepted", "delivering", "completed", "cancelled"])',
        status_text: '@pick(["待支付", "待接单", "已接单", "配送中", "已完成", "已取消"])',
        total_amount: '@float(10, 500, 2, 2)',
        goods_count: '@integer(1, 10)',
        created_at: '@datetime',
        goods: [
          {
            id: '@id',
            name: '@ctitle(5, 15)',
            image: '@image("100x100")',
            price: '@float(10, 100, 2, 2)',
            quantity: '@integer(1, 5)'
          }
        ]
      }
    ],
    total: '@integer(10, 100)',
    page: '@integer(1, 10)',
    page_size: 10
  }
})

// 下单预览（结算页）
Mock.mock(/\/api\/order\/preview/, 'post', {
  code: 0,
  message: '获取成功',
  data: {
    items: [
      {
        id: '@id',
        goods_id: '@id',
        name: '@ctitle(5, 15)',
        image: '@image("100x100")',
        price: '@float(10, 100, 2, 2)',
        quantity: '@integer(1, 3)',
        amount: '@float(10, 300, 2, 2)'
      }
    ],
    amounts: {
      goods_amount: '@float(20, 300, 2, 2)',
      freight_amount: 0,
      discount_amount: '@float(0, 50, 2, 2)',
      pay_amount: '@float(10, 300, 2, 2)'
    },
    address: {
      id: '@id',
      name: '@cname',
      phone: /^1[3-9]\d{9}$/,
      province: '@province',
      city: '@city',
      district: '@county',
      detail: '@ctitle(10, 30)'
    },
    coupons: [
      {
        id: '@id',
        name: '满100减10',
        type: 'amount',
        value: 10
      }
    ],
    remark_required: false
  }
})

// 创建订单
Mock.mock(/\/api\/order\/create/, 'post', {
  code: 0,
  message: '下单成功',
  data: {
    order_id: '@id',
    order_no: '@string("number", 16)',
    pay_amount: '@float(10, 300, 2, 2)',
    pay_params: {
      timeStamp: '@now("T")',
      nonceStr: '@string(16)',
      package: 'prepay_id=@string(24)',
      signType: 'MD5',
      paySign: '@string(32)'
    }
  }
})

// 订单取消
Mock.mock(/\/api\/order\/cancel\/\d+/, 'put', { code: 0, message: '已取消', data: true })

// 订单确认收货
Mock.mock(/\/api\/order\/confirm\/\d+/, 'put', { code: 0, message: '确认收货成功', data: true })

// 订单退款申请
Mock.mock(/\/api\/order\/refund/, 'post', { code: 0, message: '提交成功', data: true })

// 微信支付模拟
Mock.mock(/\/api\/pay\/wechat/, 'post', {
  code: 0,
  message: '支付成功',
  data: {
    paid: true,
    pay_time: '@datetime'
  }
})

Mock.mock(/\/api\/order\/detail\/\d+/, 'get', {
  code: 0,
  message: '获取成功',
  data: {
    id: '@id',
    order_no: '@string("number", 16)',
    status: '@pick(["pending_pay", "pending_accept", "accepted", "delivering", "completed", "cancelled"])',
    status_text: '@pick(["待支付", "待接单", "已接单", "配送中", "已完成", "已取消"])',
    total_amount: '@float(10, 500, 2, 2)',
    freight_amount: '@float(0, 20, 2, 2)',
    discount_amount: '@float(0, 50, 2, 2)',
    pay_amount: '@float(10, 500, 2, 2)',
    created_at: '@datetime',
    pay_time: '@datetime',
    accept_time: '@datetime',
    ship_time: '@datetime',
    complete_time: '@datetime',
    address: {
      name: '@cname',
      phone: /^1[3-9]\d{9}$/,
      province: '@province',
      city: '@city',
      district: '@county',
      detail: '@ctitle(10, 30)'
    },
    leader: {
      id: '@id',
      name: '@cname',
      phone: /^1[3-9]\d{9}$/,
      store_name: '@ctitle(5, 10)',
      address: '@ctitle(10, 30)'
    },
    goods: [
      {
        id: '@id',
        name: '@ctitle(5, 15)',
        image: '@image("100x100")',
        price: '@float(10, 100, 2, 2)',
        quantity: '@integer(1, 5)',
        total_amount: '@float(10, 500, 2, 2)'
      }
    ]
  }
})

// 团长相关Mock数据
Mock.mock(/\/api\/leader\/list/, 'get', {
  code: 0,
  message: '获取成功',
  data: {
    'list|3-8': [
      {
        id: '@id',
        name: '@cname',
        avatar: '@image("100x100")',
        store_name: '@ctitle(5, 10)',
        address: '@ctitle(10, 30)',
        service_radius: '@integer(1000, 5000)',
        commission_rate: '@float(5, 15, 1, 1)',
        rating: '@float(3, 5, 1, 1)',
        order_count: '@integer(10, 1000)',
        distance: '@integer(100, 3000)'
      }
    ]
  }
})

Mock.mock(/\/api\/leader\/commission-stats/, 'get', {
  code: 0,
  message: '获取成功',
  data: {
    today_commission: '@float(10, 500, 2, 2)',
    month_commission: '@float(100, 5000, 2, 2)',
    total_commission: '@float(1000, 50000, 2, 2)',
    today_orders: '@integer(1, 50)',
    month_orders: '@integer(10, 500)',
    total_orders: '@integer(100, 5000)'
  }
})

// 团长佣金明细
Mock.mock(/\/api\/leader\/commission-details/, 'get', {
  code: 0,
  message: '获取成功',
  data: {
    'list|10-30': [
      {
        id: '@id',
        order_no: '@string("number", 16)',
        amount: '@float(1, 200, 2, 2)',
        created_at: '@datetime',
        remark: '@ctitle(6, 16)'
      }
    ],
    total: '@integer(10, 300)'
  }
})

// 团长申请提现
Mock.mock(/\/api\/leader\/withdraw/, 'post', { code: 0, message: '申请成功', data: true })

// 团长申请入驻
Mock.mock(/\/api\/leader\/apply/, 'post', {
  code: 0,
  message: '提交成功',
  data: {
    apply_id: '@id',
    status: 'pending',
    status_text: '审核中'
  }
})

// 团长列表
Mock.mock(/\/api\/leader\/list/, 'get', () => {
  const list = Mock.mock({
    'items|10': [
      {
        id: '@id',
        name: '@cname',
        avatar: '@image("120x120")',
        store_name: '@ctitle(4, 10)·服务点',
        address: '@city(true) @county() @ctitle(3,8)号',
        rating: '@float(4, 5, 1, 1)',
        distance: '@integer(200, 8000)'
      }
    ]
  }).items
  return { code: 0, message: '获取成功', data: { list, total: 100 } }
})

// 团长详情
Mock.mock(/\/api\/leader\/info\/.+/, 'get', {
  code: 0,
  message: '获取成功',
  data: {
    id: '@id',
    name: '@cname',
    avatar: '@image("200x200")',
    store_name: '@ctitle(4, 10)·服务点',
    address: '@city(true) @county() @ctitle(3,8)号',
    rating: '@float(4, 5, 1, 1)',
    phone: /^1[3-9]\d{9}$/,
    service_radius: '@integer(1000, 5000)',
    commission_rate: '@integer(5, 15)'
  }
})

// 邀请相关Mock数据
Mock.mock(/\/api\/invite\/stats/, 'get', {
  code: 0,
  message: '获取成功',
  data: {
    total_invites: '@integer(0, 100)',
    total_commission: '@float(0, 1000, 2, 2)',
    today_invites: '@integer(0, 10)',
    today_commission: '@float(0, 100, 2, 2)',
    invite_code: '@string("number", 6)',
    invite_url: '@url'
  }
})

Mock.mock(/\/api\/invite\/ranking/, 'get', {
  code: 0,
  message: '获取成功',
  data: {
    'list|10': [
      {
        rank: '@integer(1, 10)',
        user_id: '@id',
        nickname: '@cname',
        avatar: '@image("50x50")',
        invite_count: '@integer(1, 100)',
        commission: '@float(10, 1000, 2, 2)'
      }
    ]
  }
})

// 地址相关Mock数据
Mock.mock(/\/api\/address\/list/, 'get', {
  code: 0,
  message: '获取成功',
  data: {
    'list|0-5': [
      {
        id: '@id',
        name: '@cname',
        phone: /^1[3-9]\d{9}$/,
        province: '@province',
        city: '@city',
        district: '@county',
        detail: '@ctitle(10, 30)',
        is_default: '@boolean'
      }
    ]
  }
})

// 优惠券相关Mock数据
Mock.mock(/\/api\/coupon\/my/, 'get', {
  code: 0,
  message: '获取成功',
  data: {
    'list|0-10': [
      {
        id: '@id',
        name: '@ctitle(10, 20)',
        type: '@pick(["discount", "amount"])',
        value: '@float(5, 50, 2, 2)',
        min_amount: '@float(10, 100, 2, 2)',
        start_time: '@datetime',
        end_time: '@datetime',
        status: '@pick(["unused", "used", "expired"])',
        status_text: '@pick(["未使用", "已使用", "已过期"])'
      }
    ]
  }
})

// 补充：商品分类商品列表
Mock.mock(/\/api\/goods\/category/, 'get', {
  code: 0,
  message: '获取成功',
  data: {
    'list|10-20': [
      {
        id: '@id',
        name: '@ctitle(5, 15)',
        image: '@image("200x200")',
        price: '@float(10, 100, 2, 2)',
        original_price: '@float(12, 120, 2, 2)',
        sales: '@integer(0, 5000)'
      }
    ],
    page: '@integer(1, 5)',
    total: '@integer(20, 200)'
  }
})

// 补充：商品搜索
Mock.mock(/\/api\/goods\/search/, 'get', {
  code: 0,
  message: '获取成功',
  data: {
    'list|5-15': [
      {
        id: '@id',
        name: '@ctitle(5, 15)',
        image: '@image("200x200")',
        price: '@float(10, 100, 2, 2)',
        original_price: '@float(12, 120, 2, 2)',
        sales: '@integer(0, 5000)'
      }
    ],
    page: '@integer(1, 5)',
    total: '@integer(20, 200)'
  }
})

// 补充：限时秒杀列表
Mock.mock(/\/api\/goods\/seckill/, 'get', {
  code: 0,
  message: '获取成功',
  data: {
    title: '限时秒杀',
    end_time: '@datetime',
    'goods|5-10': [
      {
        id: '@id',
        name: '@ctitle(5, 15)',
        image: '@image("200x200")',
        original_price: '@float(10, 100, 2, 2)',
        seckill_price: '@float(5, 80, 2, 2)',
        stock: '@integer(1, 200)',
        sold_count: '@integer(0, 150)'
      }
    ]
  }
})

// 补充：团长推荐商品
Mock.mock(/\/api\/goods\/leader\/\d+/, 'get', {
  code: 0,
  message: '获取成功',
  data: {
    leader_id: '@id',
    'list|6-12': [
      {
        id: '@id',
        name: '@ctitle(5, 15)',
        image: '@image("200x200")',
        price: '@float(10, 100, 2, 2)',
        original_price: '@float(12, 120, 2, 2)'
      }
    ]
  }
})

// 补充：购物车操作
Mock.mock(/\/api\/cart\/add/, 'post', { code: 0, message: '添加成功', data: true })
Mock.mock(/\/api\/cart\/update/, 'put', { code: 0, message: '更新成功', data: true })
Mock.mock(/\/api\/cart\/remove/, 'delete', { code: 0, message: '删除成功', data: true })
Mock.mock(/\/api\/cart\/clear/, 'delete', { code: 0, message: '清空成功', data: true })
Mock.mock(/\/api\/cart\/select/, 'put', { code: 0, message: '选择成功', data: true })

// 补充：订单支付（与页面接口保持一致）
Mock.mock(/\/api\/order\/pay/, 'post', {
  code: 0,
  message: '支付成功',
  data: {
    paid: true,
    pay_time: '@datetime'
  }
})

// 补充：团长信息与订单及操作
Mock.mock(/\/api\/leader\/info\/\d+/, 'get', {
  code: 0,
  message: '获取成功',
  data: {
    id: '@id',
    name: '@cname',
    avatar: '@image("100x100")',
    store_name: '@ctitle(5, 10)',
    address: '@ctitle(10, 30)',
    service_radius: '@integer(1000, 5000)',
    commission_rate: '@float(5, 15, 1, 1)',
    rating: '@float(3, 5, 1, 1)'
  }
})

Mock.mock(/\/api\/leader\/orders/, 'get', {
  code: 0,
  message: '获取成功',
  data: {
    'list|5-15': [
      {
        id: '@id',
        order_no: '@string("number", 16)',
        status: '@pick(["pending_accept","accepted","delivering","completed"])',
        price: '@float(10, 300, 2, 2)',
        created_at: '@datetime',
        user_name: '@cname',
        address: '@ctitle(10, 30)'
      }
    ],
    total: '@integer(10, 200)'
  }
})

Mock.mock(/\/api\/leader\/accept-order\/\d+/, 'put', { code: 0, message: '接单成功', data: true })
Mock.mock(/\/api\/leader\/reject-order\/\d+/, 'put', { code: 0, message: '已拒单', data: true })
Mock.mock(/\/api\/leader\/ship-order\/\d+/, 'put', { code: 0, message: '发货成功', data: true })

// 补充：地址相关（增删改设默认）
Mock.mock(/\/api\/address\/add/, 'post', {
  code: 0,
  message: '添加成功',
  data: { id: '@id' }
})
Mock.mock(/\/api\/address\/update/, 'put', { code: 0, message: '更新成功', data: true })
Mock.mock(/\/api\/address\/delete\/\d+/, 'delete', { code: 0, message: '删除成功', data: true })
Mock.mock(/\/api\/address\/default\/\d+/, 'put', { code: 0, message: '设置默认成功', data: true })

// 补充：优惠券列表/领取/使用
Mock.mock(/\/api\/coupon\/list/, 'get', {
  code: 0,
  message: '获取成功',
  data: {
    'list|5-12': [
      {
        id: '@id',
        name: '@ctitle(8, 16)',
        type: '@pick(["discount", "amount"])',
        value: '@float(5, 50, 2, 2)',
        min_amount: '@float(50, 200, 2, 2)',
        start_time: '@datetime',
        end_time: '@datetime'
      }
    ]
  }
})
Mock.mock(/\/api\/coupon\/receive\/\d+/, 'post', { code: 0, message: '领取成功', data: true })
Mock.mock(/\/api\/coupon\/use\/\d+/, 'put', { code: 0, message: '使用成功', data: true })

// 补充：邀请海报与奖励
Mock.mock(/\/api\/invite\/poster/, 'get', {
  code: 0,
  message: '获取成功',
  data: {
    poster: '@image("600x1000")',
    invite_code: '@string("number", 6)',
    invite_url: '@url'
  }
})
Mock.mock(/\/api\/invite\/rewards/, 'get', {
  code: 0,
  message: '获取成功',
  data: {
    'list|3-8': [
      {
        id: '@id',
        name: '@ctitle(5, 12)',
        amount: '@float(1, 50, 2, 2)',
        created_at: '@datetime'
      }
    ]
  }
})